<?php
/**
 * Trieda na routovanie requestov
 * @author Tomas Srna
 * @package bakalarka
 */

class Router
{
	/**
	 * Zakazeme tvorbu instancie
	 */
	protected function __construct() {}
	
	/**
	 * Zakazeme klonovanie
	 */
	protected function __clone() {}
	
	/**
	 * Parsovanie URI
	 * @param string $request_uri 		URI retazec
	 * @param string &$controller		Nazov controllera pre zapis
	 * @param string &$action			Retazec akcie pre zapis
	 * @param array &$args				Pole argumentov pre zapis
	 * @return void						Funkcia nic nevracia
	 */
	protected static function parse($request_uri, 
		&$controller, &$action, array& $args)
	{
		// Odstranme APPBASE zo zaciatku
		if(strpos($request_uri, APPBASE) === 0)
			$request_uri = substr($request_uri, strlen(APPBASE));
		// Berieme iba po '?'
		if($p = strpos($request_uri, '?'))
			$request_uri = substr($request_uri, 0, $p); 
		$request_uri = trim($request_uri, '/');
		$route = explode('/', $request_uri);
		
		$controllerName = array_shift($route);
		if($controllerName == NULL) $controllerName = 'index';
		$controllerName = str_replace(array('-', '_'), ' ', $controllerName);
  		$controllerName = ucwords($controllerName); 
  		$controllerName = str_replace(' ', '', $controllerName);

		$controller = $controllerName.'Controller';
		if($controller == 'Controller' ||
			 !file_exists(APPROOT.'controller'.DS.$controller.'.php'))
			$controller = 'ErrorController';

		if(/*$controller == 'ErrorController' ||*/ 
			($action = array_shift($route)) == NULL)
			$action = 'index';
			
		$args = $route;
	}
	
	/**
	 * Routovanie requestu
	 * @param string $request_uri		Request URI
	 * @return void						Funkcia nic nevracia
	 */
	public static function route($request_uri)
	{
		$controller = $action = "";
		$args = array();
		self::parse($request_uri, $controller, $action, $args);
		
		//echo "request_uri: $request_uri; controller: $controller; action: $action";
		
		/**
		 * @var $controllerObject Controller
		 */
		$controllerObject = @call_user_func(array($controller, 'instance'));
		
		if(!($controllerObject instanceof Controller))
			throw new Exception('L::invalidController');
			
		array_unshift($args, $controller, $action);
		$controllerObject->args = $args;
		
		$controllerObject->preDispatch();
		if(!method_exists($controllerObject, $action))
		{
			unset($controllerObject);
			
			$controller = 'ErrorController';
			$action = 'index';
			
			$controllerObject = call_user_func(array($controller, 'instance'));
		}
		$controllerObject->postDispatch();
		
		$controllerObject->$action();
	}
} 
